<?php
// +----------------------------------------------------------------------
// | xiongrui [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.xiongrui.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.xiongrui.cn>
// +----------------------------------------------------------------------

namespace app\index\controller;
use app\common\controller\Fornt;
use app\common\model\Goodsrule;
use app\common\model\Cart as CartModel;
use app\common\model\Goods;
use app\common\model\Goodscat;
use app\common\model\AddressNew;
use app\common\model\DeliveryArea;
use app\common\model\DeliveryTime;
use app\common\model\CouponList;
use app\common\model\Place;
use think\Request;
use think\Cache;

class Cart extends Fornt{
    /**
     * 配送页面购物车金阳配送
     * @return [type] [description]
     */
	public function index(){
		cookie('addressbackurl',  url('index/cart/index'));
		// if(!is_numeric(cookie('place_id'))){
		// 	$this->error('未选择区域', url('index/index/index'));
		// }
		//判断默认地址运费是否改变
		$address =  $this->getJudgeFreight($place_id = 1);

		//读取地址
		// $place = db('place')->where(['id'=>cookie('place_id')])->find();
		// if($address['place_id'] != $place['id']){
		// 	parent::setFreight($place['latlng'], $place['freight'], $place['km'], $place['unit'], $place['id']);
		// }
		if(strstr($address['address_full'], '白云区') || strstr($address['address_full'], '观山湖区')){
			$this->assign('zhichi', 1);
		}else{
			$this->assign('zhichi', 1);
		}
// 		}else{
// 		    $this->assign('zhichi', 2);
// 		}

		$cinfo = CartModel::getNumAndPrice(['user_id'=>USER_ID]);
		//判断是否是会员, 是会员打折
		$cinfo['price'] = parent::isMemberAndDiscount($cinfo['price']);

		//运费补贴
		$subsidy = getSubsidy($cinfo['price'], $address['freight']);
		//购物车总价格
		$cartPrice = $cinfo['price'];

		$this->assign('cartSum', $cinfo['num']);
		$this->assign('cartCountprice', $cartPrice);
		$this->assign('subsidy', $subsidy);
		$this->assign('freight_art_price', $cinfo['freight_art_price']);
		$this->assign('cartGoodId', $cinfo['good_id_arr']);
		$this->assign('cartlist', $cinfo['list']);
		$this->assign('Goodscatlist', $Goodscatlist);
		$this->assign('address', $address);

		if(cookie('?couponlist_id')){


			$couponinfo = CouponList::where('id', cookie('couponlist_id'))->find();

			if($couponinfo['status'] == 1 || $cinfo['price']< $couponinfo['total']){
				cookie('couponlist_id', null);
			}

		}

		//判断是否只有活动商品【如果只有活动商品，取消运费补贴】

		parent::isEventsGoods($cinfo['goods_feature']);

		return $this->fetch();
	}

	
	/**
	 * 配送页面购物车包邮配送
	 * @return [type] [description]
	 */
	public function indexbaoyou(){
	    cookie('addressbackurl',  url('index/cart/indexbaoyou'));
	    cookie('way', 2);
	    // if(!is_numeric(cookie('place_id'))){
	    // 	$this->error('未选择区域', url('index/index/index'));
	    // }
	    //判断默认地址运费是否改变
	    $address =  $this->getJudgeFreight($place_id = 1);
	
	    //读取地址
	    // $place = db('place')->where(['id'=>cookie('place_id')])->find();
	    // if($address['place_id'] != $place['id']){
	    // 	parent::setFreight($place['latlng'], $place['freight'], $place['km'], $place['unit'], $place['id']);
	    // }
	    if(strstr($address['address_full'], '白云区') || strstr($address['address_full'], '观山湖区')){
	        $this->assign('zhichi', 1);
	    }else{
	        $this->assign('zhichi', 1);
	    }
	    // 		}else{
	    // 		    $this->assign('zhichi', 2);
	    // 		}
	
	    $cinfo = CartModel::getNumAndPrice(['user_id'=>USER_ID]);
	    //判断是否是会员, 是会员打折
	    $cinfo['price'] = parent::isMemberAndDiscount($cinfo['price']);
	
	    //运费补贴
	    $subsidy = getSubsidy($cinfo['price'], $address['freight']);
	    //购物车总价格
	    $cartPrice = $cinfo['price'];
	//运费设为0freight
	    $address['freigh']=123;
	    $this->assign('cartSum', $cinfo['num']);
	    $this->assign('cartCountprice', $cartPrice);
	    $this->assign('subsidy', $subsidy);
	    $this->assign('freight_art_price', $cinfo['freight_art_price']);
	    $this->assign('cartGoodId', $cinfo['good_id_arr']);
	    $this->assign('cartlist', $cinfo['list']);
	    $this->assign('Goodscatlist', $Goodscatlist);
	    $this->assign('address', $address);
	
	    if(cookie('?couponlist_id')){
	
	
	        $couponinfo = CouponList::where('id', cookie('couponlist_id'))->find();
	
	        if($couponinfo['status'] == 1 || $cinfo['price']< $couponinfo['total']){
	            cookie('couponlist_id', null);
	        }
	
	    }
	
	    //判断是否只有活动商品【如果只有活动商品，取消运费补贴】
	
	    parent::isEventsGoods($cinfo['goods_feature']);
	
	    return $this->fetch();
	}


	/**
	 * 配送页面购物车全市配送
	 * @return [type] [description]
	 */
	public function delivery(){
		cookie('addressbackurl',  url('index/cart/delivery'));

		//判断默认地址运费是否改变
		$address =  $this->getJudgeFreight();
		//读取购物车信息
		$cinfo = CartModel::getNumAndPrice(['user_id'=>USER_ID]);

		if($cinfo['price'] < config('initialdeliveryprice')){
			$this->error('未满足起送价格');
		}

		//优惠券设置
		$this->setCoupon($cinfo['price']);

		//判断是否是会员
		$phone = db('WxUser')->where('id', USER_ID)->value('phone');
 	 	$isMember = 0;
 	 if($phone){
 		 $isMember = 1;
 	 }
 	 $this->assign('isMember', $isMember);

	 //运费补贴
	 $subsidy = getSubsidy($cinfo['price'], $address['freight']);
	 //购物车总价格
	 $cartPrice = $cinfo['price'];




		$this->assign([
			'cartinfo' => $cinfo,
			'address' => $address,
			'cartCountprice'=>$cartPrice+$cinfo['pack_price'],
			'subsidy' => $subsidy
		]);
		return $this->fetch();
	}

	/**
	 * 包邮商品
	 * @return [type] [description]
	 */
	public function frank(){
		cookie('addressbackurl',  url('index/cart/frank'));

		//判断默认地址运费是否改变
		$address =  $this->getJudgeFreight();
		//读取购物车信息
		$cinfo = CartModel::getNumAndPrice(['user_id'=>USER_ID]);

		if($cinfo['price'] < config('initialdeliveryprice')){
			$this->error('未满足起送价格');
		}

		//优惠券设置
		$this->setCoupon($cinfo['price']);

		//判断是否是会员
		$phone = db('WxUser')->where('id', USER_ID)->value('phone');
 	 	$isMember = 0;
 	 if($phone){
 		 $isMember = 1;
 	 }
 	 $this->assign('isMember', $isMember);

	 $address['freight'] = 0;
	 //运费补贴
	 $subsidy = getSubsidy($cinfo['price'], $address['freight']);
	 //购物车总价格
	 $cartPrice = $cinfo['price'];




		$this->assign([
			'cartinfo' => $cinfo,
			'address' => $address,
			'cartCountprice'=>$cartPrice+$cinfo['pack_price'],
			'subsidy' => $subsidy
		]);
		return $this->fetch();
	}



	//包邮商品
	public function pinkage($rule_id = null){
		if($rule_id){
			cookie('addressbackurl',  url('index/cart/pinkage', ['rule_id'=> $rule_id]));
			$info = model('Goodsrule')->find($rule_id);
			$address = model('AddressNew')->where(['type'=>0,'status'=>1, 'defaults'=>1, 'user_id'=>USER_ID])->find();

			$this->assign('info', $info);
			$this->assign('address', $address);

			return $this->fetch();
		}
	}


//判断默认地址运费是否改变
	public function getJudgeFreight($place_id = null){
		$addressMap = [
			'user_id'=>USER_ID,
			'type'=> cookie('address_type') ? cookie('address_type') : 0,
			'defaults'=>1
		];
		$addressInfo = db('AddressNew')->where($addressMap)->find();
		if($addressInfo){
			//地址出错
			if(!$addressInfo['latlng']){
				$this->error('地址不完整', url('address/add', ['id'=>$addressInfo['id']]));
			}


			//判断最小距离
				if($place_id){
					$place = db('place')->find($place_id);
				}else{
					$place = minDistance($addressInfo['latlng']);
				}



				$freight = calculateFreight($addressInfo['disparity'], $place['freight'], $place['km'], $place['unit'], $place['id']);


				if($freight != $addressInfo['freight'] || $place['id'] != $addressInfo['place_id']){
						//调用地图api，更新用户默认地址
						$distance =  getMapdistance($place['latlng'] ,$addressInfo['latlng']);

						$freight = calculateFreight($distance, $place['freight'], $place['km'], $place['unit'], $place['id']);

						$return = db('AddressNew')->where('id', $addressInfo['id'])->update(['place_id' => $place['id'],'freight'=>$freight, 'disparity'=>$distance]);
						if($return){
							$addressInfo = db('AddressNew')->where('id', $addressInfo['id'])->find();
						}

				}
		}

		return $addressInfo;

	}



	/**
	 * 直发页面购物车
	 * @return [type] [description]
	 */
	public function placepinkage(){



		//读取购物车信息
		$cinfo = CartModel::getNumAndPrice(['user_id'=>USER_ID]);

		//获取默认地址
		$addressMap = [
			'user_id'=>USER_ID,
			'type'=> cookie('address_type') ? cookie('address_type') : 0,
			'defaults'=>1
		];
		$address = AddressNew::get($addressMap);
		if($address){
			$address['freight'] = 0;
		}

		//优惠券设置
		$this->setCoupon($cinfo['price']);


		$this->assign([
			'cartinfo' => $cinfo,
			'address' => $address,
			'cartCountprice'=>$cinfo['price']
		]);
		return $this->fetch();
	}
	/**
	 * 通过地图api动态设置运费
	 * @return [type] [description]
	 */
	protected function addressSetFreight(){
		//设置默认的发货地址id
		if(empty(cookie('place_id'))){
			cookie('place_id', 1);
		}
		//读取地址 并 设置运费
		//运费根据地图api来判断
		$address = AddressNew::where(['user_id'=>USER_ID,'defaults'=>1])->find();
		$place = Place::where(['id'=>cookie('place_id')])->find();
		//如果cookie('place_id')获取的发货地址id 与 数据库中地址id 不一致的话 重新运算运费
		if($address['place_id'] != $place['id']){
			$setFreightResult = parent::setFreight($place['latlng'], $place['freight'], $place['km'], $place['unit'], $place['id']);
			if(!$setFreightResult){
				$this->error('获取地址失败，请稍后再尝试');
			}
		}
	}
	/**
	 * 设置优惠券【优惠券判断】
	 * @param [type] $price [购物车总价格]
	 */
	protected function setCoupon($price){
		if(cookie('?couponlist_id')){
			//已保存的优惠券金额
			//如果优惠券金额大于购物车金额，取消cookie
			$couponinfo = CouponList::where('id', cookie('couponlist_id'))->find();

			if($couponinfo['status'] == 1 || $price< $couponinfo['total']){
				cookie('couponlist_id', null);
			}
		}
	}

	/**
	 * 支付页面
	 * @return [type] [description]
	 */
	public function pay(){
		update_session(USER_ID);
		$this->assign('xstatus', input('xstatus'));
		$this->assign('title', '付款');
		return $this->fetch();
	}
	
	

	/**
	 * 支付页面测试页面
	 * @return [type] [description]
	 */
	public function paytest(){

	    

         update_session(USER_ID);

 	    $this->assign('info', USER_ID);
	    $this->assign('xstatus', input('xstatus'));
	    $this->assign('title', '付款');
	    return $this->fetch();
	}
	

	public function add($id = null){
    if (!$id) {
			return $this->error("非法操作！");
		}
    if (Request::instance()->isAjax()){
      $ruleinfo = Goodsrule::get($id);
      if($ruleinfo){
        $map['user_id'] = USER_ID;
        $map['rule_id'] = $id;
        $cartinfo = CartModel::get($map);

				//库存判断
				if($ruleinfo['stock'] == 0){
					$this->error('该商品库存不足！');
				}

				//团购限购
				if($ruleinfo['quota'] >0 && !empty(config('grouptime')) ){

					//检查对应的团购日期（config('grouptime')）是否已经购买
					// $orderQuotaNum = db('OrderShoplist')->where(['user_id'=>USER_ID, 'rule_id'=>$ruleinfo['id'], 'group_time'=>config('grouptime')])->count('num');
					// $cartQuotaNum = db('cart')->where(['user_id'=>USER_ID, 'rule_id'=>$ruleinfo['id']])->count('num');
					// if(($orderQuotaNum+$cartQuotaNum) >= $ruleinfo['quota']){
					// 	$this->error('该商品限购'.$ruleinfo['quota'].'个');
					// }
					if($cartinfo['num'] >= $ruleinfo['quota']){
						$this->error('该商品限购'.$ruleinfo['quota'].'份');
					}
				}
				//判断商品是否是限购类型
				$goodsInfo = Goods::get($ruleinfo->goods_id);
				$goods_type = Goodscat::where('id', $goodsInfo['cat_id'])->value('goods_type');
				if($goods_type == 3){
					if($cartinfo->num>=1){
						$this->error('该商品每个用户限购一件！');
					}
					//判断是否已经购买
					$bought_userids = explode(",",	$goodsInfo['bought_userids']);

					if(in_array(USER_ID , $bought_userids)){
						$this->error('你已经购买过该商品！');
					}
					$goodsInfo['bought_userids'] .= ','.USER_ID;
					$goodsInfo->save();
				}

        if($cartinfo){
          $cartinfo->num = $cartinfo->num+1;

					if($ruleinfo['stock'] < $cartinfo->num){
						$this->error('该商品库存不足！');
					}

          if (false !== $cartinfo->save()){
						return $this->jsonDate($cartinfo);
          }else{
            return $cartinfo->getError();
          }
        }else{
          $data['good_id'] = $ruleinfo->goods_id;
          $data['rule_id'] = $ruleinfo->id;
          $data['rule_name'] = $ruleinfo->rule_name;
          $data['user_id'] = USER_ID;
          $data['good_price'] = $ruleinfo->rule_price;
          $data['good_name'] = get_table_field($ruleinfo->goods_id ,'id' ,'good_name', 'goods');
          $data['num'] = 1;
					$data['shop_id'] = $goodsInfo->shop_id;
					$data['shop_name'] = get_table_field($goodsInfo->shop_id ,'id' ,'shopname', 'goodshops');
					$data['cost_price'] = $ruleinfo->cost_price;
					$data['agent_price'] = $ruleinfo->agent_price;
					$data['goodsmodel_id'] = cookie('goodsmodel_id');
					if($goodsInfo->good_feature){
						$data['goods_feature'] = $goodsInfo->good_feature;
					}


          if ($result = CartModel::create($data)) {
							return $this->jsonDate($result);
          } else {
              return $this->error("添加购物车失败！");
          }
        }
      }else{
        return $this->error("非法操作！");
      }
    }
	}

	public function minus($id = null){
		if (!$id) {
			return $this->error("非法操作！");
		}
		if (Request::instance()->isAjax()){
			$info = CartModel::get($id);

			//判断商品是否是限购类型
			$goodsInfo = Goods::get($info->good_id);
			$goods_type = Goodscat::where('id', $goodsInfo['cat_id'])->value('goods_type');
			if($goods_type == 3){
				//判断是否已经购买
				$bought_userids = explode(",",	$goodsInfo['bought_userids']);
				if(in_array(USER_ID , $bought_userids)){
				$goodsInfo['bought_userids'] =	array_merge(array_diff($bought_userids, array(USER_ID)));
				$goodsInfo['bought_userids'] = implode(",", $goodsInfo['bought_userids']);

				$goodsInfo->save();
				}

			}


			if($info->num > 1){
				$info->num = $info->num-1;
				$info->save();
				return $this->jsonDate($info);
			}else{
				$good_id = CartModel::where('id',$id)->value('good_id');
				CartModel::destroy($id);
				return $this->jsonDate(null,$good_id);
			}
		}
	}

  public function clear(){
    if (Request::instance()->isAjax()){
      $map['user_id'] = USER_ID;
      $result = CartModel::destroy($map);
     if ($result) {
         return 1;
     } else {
         return 0;
     }
    }
  }

	public function getCartlist(){
		if (Request::instance()->isAjax()){
			$map['user_id'] = USER_ID;
			$cartlist = CartModel::all($map);
			return json($cartlist);
    }
	}

	public function jsonDate($Obj = null,$good_id = null){
		if($Obj){
			$jsonData['id'] = $Obj->id;
			$jsonData['good_id'] = $Obj->good_id;
			$jsonData['one_price_total'] = $Obj->good_price*$Obj->num;
			$jsonData['one_num'] = $Obj->num;
			$cinfo = CartModel::getNumAndPrice(['user_id'=>USER_ID,'good_id'=>$Obj->good_id]);
			$jsonData['num'] = $cinfo['num'];
		}else{
			$cinfo = CartModel::getNumAndPrice(['user_id'=>USER_ID,'good_id'=>$good_id]);
			if($cinfo){
					$jsonData['num'] = $cinfo['num'];
			}else{
					$jsonData['num'] = 0;
			}
			$jsonData['one_num'] = 0;
		}
		$cinfo = CartModel::getNumAndPrice(['user_id'=>USER_ID]);
		$jsonData['total'] = $cinfo['price'];
		$jsonData['tnum'] = $cinfo['num'];


		$jsonData['delivery_text'] = '<a href="javascript:;"  class="submitbutton tgxd">去结算</a>';



		if(cookie('init_price') > 0 ){
			$cj = $jsonData['total']-cookie('init_price');

			if($cinfo['num'] = 0){

				$jsonData['delivery_text'] = '<a href="javascript:;"  class="submitbutton">'.cookie('init_price').'元起送</a>';
			}elseif ($cj < 0) {
				$jsonData['delivery_text'] = '<a href="javascript:;"  class="submitbutton">还差'.abs($cj).'元</a>';
			}else{
				$jsonData['delivery_text'] = '<a href="javascript:;" data-url="/index/cart/delivery.html" class="submitbutton tgxd">去结算</a>';
			}

		}


		return json($jsonData);
	}




	/**
	 * 购物信息状态cookie改变
	 * Author: xiongrui <394914567@qq.com> <http://www.xiongruirui.cn>
	 */
	 public function changecookie(){
		 if(IS_GET){
				$name = input('get.name');
				$val = input('get.val');
				if(!empty($name) && !empty($val)){
					cookie($name, $val, 360);
					$this->success('更新成功');
				}
		 }
	 }


	 /**
 	 * 自定义页面付款
 	 * @return [type] [description]
 	 */
 	public function custompayment(){
 		//通过发货地址动态设置运费
 		//$this->addressSetFreight();


 		//获取默认地址
 		$address = AddressNew::get(['user_id'=>USER_ID,'defaults'=>1]);

 		//优惠券设置
 		$this->setCoupon(Cache::get('custom_price'));


 		$this->assign([
 			'custom_title' => Cache::get('custom_title'),
 			'address' => $address,
 			'cartCountprice'=>Cache::get('custom_price')
 		]);
 		return $this->fetch();
 	}


	public function qiye($cid = null){
		$info = parent::setQiyeCommon();

		//获取默认用户信息

		$qmap = [
			'uid'=>USER_ID,
			'defaults'=>1,
			'company_id'=>$cid
		];
		$qiyeUserinfo = model('Qiyeuser')->where($qmap)->find();

		$this->assign([
			'companyInfo' => $info['companyInfo'],
			'cartinfo' => $info['cinfo'],
			'qiyeUserinfo' => $qiyeUserinfo,
			'cartCountprice'=>$info['cinfo']['price']+$info['cinfo']['pack_price']
		]);
		return $this->fetch();

	}
	/**
	 * 取消订单
	 * @return [type] [description]
	 */
	public function cancel(){

	}

}
